<?php
namespace App\Http\Controllers\User;

use AlibabaCloud\Client\AlibabaCloud;
use App\Http\Libs\StoreForget;
use App\Models\BannerModel;
use Illuminate\Http\Request;
use App\Models\GvrpModel;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use App\Models\UserModel;
use Tymon\JWTAuth\Facades\JWTAuth;


class LoginController extends Controller{

    /**
     * 测试登录接口
     */
    public function test_login(Request $request,UserModel $userModel){
        try{
            $account = $request->input('phone');
            $password = $request->input('password');
            $userObj = $userModel::where('phone','=',$account)->first();

            if(!$userObj){
                throw new \Exception('账号不存在');
            }

            if(!Hash::check($password,$userObj->password)){
                throw new \Exception('密码错误');
            }

            $token = JWTAuth::fromUser($userObj);

            return response() -> json([
                'error_code' => 0,
                'msg' => '测试登录成功',
                'data' => [
                    'access_token' => $token,
                    'user'=>$userObj,
                    'expires_in' => auth('user_api') -> factory()->getTTL() * 60
                ]
            ]);

        }catch(\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage(),
                'data' => null
            ]);
        }

    }


    /**
     * @method post
     * xiaochengxu微信授权登录
     */
    public function weixin(Request $request,UserModel $userModel){
        try{


            // 获取code
            $code = $request -> input('code');

            // 获取签名 signature，rawData，iv，encryptedData
            $signature = $request -> input('signature','');

            // 获取数据包
            $rawData = $request -> input('rawData','');

            $iv = $request -> input('iv','');
            $encryptedData = $request -> input('encryptedData','');

            $appid = 'wx6f0664b570aad1ad';
            $appsecret = '94c7fb10dfdd1ec9ffa128e8998cd12e';

            // 获取用户信息
            $res = httpCurl("https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code");

            $res = json_decode($res,true);
            // 说明没有获取到openid
            if(empty($res['openid'])){
                throw new \Exception($res['errmsg']);
            }

            // 获取session_key
            $sessionKey = $res['session_key'];

            // 拼接签名
            $signature2 = sha1($rawData . $sessionKey);

            // 验证签名是否合法
            if($signature != $signature2){
                throw new \Exception('签名不合法');
            }

            //var_dump($sessionKey);die;
            $pc = new \WXBizDataCrypt($appid,$sessionKey);

            $errCode = $pc -> decryptData($encryptedData,$iv,$data);

            //var_dump($errCode);die;
            if ($errCode == 0) {
                // 将json数据转为数组
                //var_dump($data);die;
                $data = json_decode($data,true);
                //dump($data);die;
            } else {
                switch ($errCode){
                    case -41001:
                        throw new \Exception('encodingAesKey 非法');
                        break;

                    case -41003:
                        throw new \Exception('aes 解密失败');
                        break;

                    case -41004:
                        throw new \Exception('解密后得到的buffer非法');
                        break;

                    case -41005:
                        throw new \Exception('base64加密失败');
                        break;

                    case -41016:
                        throw new \Exception('base64解密失败');
                        break;

                    default:
                        throw new \Exception('未知错误');
                        break;
                }
            }

            // 获取openid
            $weappOpenid = $res['openid'];

            // 验证用户是否已经存在
            $userObj = $userModel->where('openid',$weappOpenid) -> first();

            if(!empty($userObj)){

                // 存在用户 直接登录

                $token = JWTAuth::fromUser($userObj);

                return response() -> json([
                    'error_code' => 0,
                    'msg' => '登录成功',
                    'data' => [
                        'access_token' => $token,
                        'token_type' => 'bearer',
                        //'wx_name' => $userObj -> nicheng,
                        'user'=>$userObj,

                        //'wx_head'=> 'http://xc.fngc.shop/'.$userObj -> head_img,
                        'expires_in' => auth('user_api') -> factory() -> getTTL() * 60
                    ]
                ]);

            }

            return returnMsg(400,'授权失败');

        }catch (\Exception $e){
            //dd($e);
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage(),
                'data' => null
            ]);
        }
    }


    public function banner(){
        $banner = new BannerModel();
        $data = $banner->get();
        return returnMsg(0,'获取成功',$data);
    }


    /**
     * 微信授權+手機驗證碼註冊
     */
    public function weixin_recharge(Request $request,UserModel $userModel){
        try{

            // 验证规则
            $rule = [
                'wx_code' => 'required',
                'phone' => 'required',
                'phone_code' => 'required',
                'signature' => 'required',
                'rawData' => 'required',
                'iv' => 'required',
                'encryptedData' => 'required',
            ];
            // 验证信息
            $message = [
                'wx_code.required' => '微信code不能为空',
                'phone.required' => '手機號不能',
                'phone_code.required' => 'code不能为空',
                'signature.required' => '微信signature不能为空',
                'rawData.required' => '微信rawData不能为空',
                'iv.required' => '微信iv不能为空',
                'encryptedData.required' => '微信encryptedData不能为空',
            ];
            $validator = Validator::make($request -> all(),$rule,$message);
            if($validator -> fails()){
                throw new \Exception($validator -> errors() -> first());
            }

            // 獲取手機號碼
            $phone = $request -> input('phone');

            // 驗證該手機號碼是否已經註冊
            $memberObj = $userModel -> where('phone','=',$phone) -> first();
            if($memberObj){
                throw new \Exception('該手機號碼已註冊');
            }

            // 获取code
            $phone_code = $request -> input('phone_code');

            // 验证验证码是否合法
            StoreForget::checkCode($phone,$phone_code);

            // 获取签名 signature，rawData，iv，encryptedData
            $signature = $request -> input('signature','');

            // 获取数据包
            $rawData = $request -> input('rawData','');

            $iv = $request -> input('iv','');
            $encryptedData = $request -> input('encryptedData','');

            $appid = 'wx6f0664b570aad1ad';
            $appsecret = '94c7fb10dfdd1ec9ffa128e8998cd12e';

            $wx_code =  $request->input('wx_code');

            // 获取用户信息
            $res = httpCurl("https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$wx_code&grant_type=authorization_code");

            $res = json_decode($res,true);
            // 说明没有获取到openid
            if(empty($res['openid'])){
                throw new \Exception($res['errmsg']);
            }

            // 获取session_key
            $sessionKey = $res['session_key'];

            // 拼接签名
            $signature2 = sha1($rawData . $sessionKey);

            // 验证签名是否合法
            if($signature != $signature2){
                throw new \Exception('签名不合法');
            }


            $pc = new \WXBizDataCrypt($appid,$sessionKey);

            $errCode = $pc -> decryptData($encryptedData,$iv,$data);

            if ($errCode == 0) {
                // 将json数据转为数组

                $data = json_decode($data,true);

            } else {
                switch ($errCode){
                    case -41001:
                        throw new \Exception('encodingAesKey 非法');
                        break;

                    case -41003:
                        throw new \Exception('aes 解密失败');
                        break;

                    case -41004:
                        throw new \Exception('解密后得到的buffer非法');
                        break;

                    case -41005:
                        throw new \Exception('base64加密失败');
                        break;

                    case -41016:
                        throw new \Exception('base64解密失败');
                        break;

                    default:
                        throw new \Exception('未知错误');
                        break;
                }
            }

            // 获取openid
            $weappOpenid = $res['openid'];

            // 查找會員是否存在
            $user = $userModel
                -> where('openid','=',$weappOpenid)
                -> first();

            if($user){
                throw new \Exception('該微信已有綁定賬號');
            }

                $avatarUrl = '';
                // 获取图片信息
                $param = @getimagesize($data['avatarUrl']);

                // 存在参数则获取后缀名
                if($param){

                    // 获取文件后缀名
                    $suffix = explode('/',$param['mime'])[1];

                    // 定义保存的路径
                    $avatarUrl = 'avatar/' . date('Ymd');

                    // 验证文件夹是否存在
                    if(!is_dir('upload/' . $avatarUrl)){
                        // 不存在则创建
                        mkdir('upload/' . $avatarUrl,0777,true);
                    }

                    // 获取图片名称
                    $imagesName = md5(time()). '.' . $suffix;

                    $avatarUrl .= '/' . $imagesName;
                    // 下载图片
                    downloadImages($data['avatarUrl'],'upload/' . $avatarUrl);
                }

                $userModel -> phone = $request->input('phone');
                $userModel -> openid = $weappOpenid;
                $userModel -> password = $request->input('password');
                $userModel -> head_img = $avatarUrl;
                $userModel -> nickName = $data['nickName'] ? $data['nickName'] : '';
                $userModel -> gender = $data['gender'] ? $data['gender'] : 2;
                $userModel -> created_at = time();
                $res = $userModel -> save();

                if(!$res){
                    throw new \Exception('授权异常,请重新授权');
                }

                $token = JWTAuth::fromUser($userModel);


            return response() -> json([
                'error_code' => 0,
                'msg' => '注册成功',
                'data' => [
                    'access_token' => $token,
                    'token_type' => 'bearer',

                    'user'=>$userModel,

                    'expires_in' => auth('user_api') -> factory()->getTTL() * 60
                ]
            ]);
        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage(),
                'data' => null
            ]);
        }

    }

    //获取验证码
    public function phone_code(Request $request){
            try{

                // 验证规则
                $rule = [
                    'phone' => [
                        'required',
                        'regex:/^1\d{10}$/'
                    ]
                ];

                // 验证信息
                $message = [
                    'phone.required' => '手机号码不能为空',
                    'phone.regex' => '手机号码格式不正确',
                ];

                $validator = Validator::make($request -> all(),$rule,$message);
                if($validator -> fails()){
                    throw new \Exception($validator -> errors() -> first());
                }

                // 获取手机号码
                $phone = $request -> input('phone');

                // 获取验证码
                $code = getNumCode(6);

                // 获取手机验证码
                StoreForget::getCode($phone,$code);

                // 获取阿里云手机验证码
                AlibabaCloud::accessKeyClient('LTAI4FryuatvWeiZQAYCzCfF','L5iYIb541vwYHachLdkpcgDIkBBo5o')
                    -> regionId('cn-shenzhen')
                    -> asDefaultClient();

                // 设置参数
                $data = [
                    'code' => $code
                ];

                $result = AlibabaCloud::rpc()
                    -> product('Dysmsapi')
                    -> scheme('http')
                    -> version('2017-05-25')
                    -> action('SendSms')
                    -> method('POST')
                    -> host('dysmsapi.aliyuncs.com')
                    -> options([
                        'query' => [
                            'RegionId' => "default",
                            'PhoneNumbers' => $phone,
                            'SignName' => '维狐网络',
                            'TemplateCode' => 'SMS_165415738',
                            'TemplateParam' => json_encode($data),
                        ],
                    ])
                    -> request();

                $result = $result -> toArray();

                if($result['Message'] != 'OK' || $result['Code'] != 'OK'){
                    Cache::forget(env('ALI_STORE_CACHE_PREFIX') . $phone);
                    // Cache::forget(env('ALI_STORE_CACHE_EXPIRE_KEY') . $phone);
                    throw new \Exception($result['Message']);
                }

                return response() -> json([
                    'error_code' => 0,
                    'msg' => '验证码发送成功'
                ]);
            }catch (\Exception $e){
                return response() -> json([
                    'error_code' => 400,
                    'msg' => $e -> getMessage()
                ]);
            }
    }

    /**
     * 修改密码 通过短信
     * @method post
     */
    public function edit_password(Request $request,UserModel $userModel){

        try{

            // 验证规则
            $rule = [
                'phone' => [
                    'required',
                    'regex:/^1\d{10}$/'
                ],
                'code' => 'required',
                'password' => 'required',
            ];

            // 验证信息
            $message = [
                'phone.required' => '手机号码不能为空',
                'phone.regex' => '手机号码格式不正确',
                'code.required' => '验证码不能为空',
                'password.required' => '密码不能为空',
            ];

            $validator = Validator::make($request -> all(),$rule,$message);
            if($validator -> fails()){
                throw new \Exception($validator -> errors() -> first());
            }

            // 手机号码
            $phone = $request -> input('phone');

            // 获取验证码
            $code = $request -> input('code');

            // 获取密码
            $password = $request -> input('password');

            // 验证验证码是否合法
            StoreForget::checkCode($phone,$code);

            // 查找是否存在
            $userObj = $userModel -> where('phone','=',$phone) -> first();
            if(!$userObj){
                throw new \Exception('用户异常');
            }

            $userObj -> password = $password;
            $res = $userObj -> save();

            if(!$res){
                throw new \Exception('密码重置失败');
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '密码重置成功,请牢记新密码'
            ]);

        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }
    }

    /**
     * 修改密码 通过短信
     * @method post
     */
    public function edit_phone(Request $request,UserModel $userModel){

        try{

            // 验证规则
            $rule = [
                'phone' => [
                    'required',
                    'regex:/^1\d{10}$/'
                ],
                'code' => 'required',
               // 'password' => 'required',
            ];

            // 验证信息
            $message = [
                'phone.required' => '手机号码不能为空',
                'phone.regex' => '手机号码格式不正确',
                'code.required' => '验证码不能为空',
                //'password.required' => '密码不能为空',
            ];

            $validator = Validator::make($request -> all(),$rule,$message);
            if($validator -> fails()){
                throw new \Exception($validator -> errors() -> first());
            }

            // 手机号码
            $phone = $request -> input('phone');

            // 获取验证码
            $code = $request -> input('code');

            // 获取密码
          //  $password = $request -> input('password');

            // 验证验证码是否合法
            StoreForget::checkCode($phone,$code);

            // 查找是否存在
            $userObj = $userModel -> where('phone','=',$phone) -> first();
            if(!$userObj){
                throw new \Exception('用户异常');
            }

            $userObj -> phone = $phone;
            $res = $userObj -> save();

            if(!$res){
                throw new \Exception('手机号码重置失败');
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '手机号码重置成功'
            ]);

        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }
    }

    //获取注册协议
    public function gvrp(GvrpModel $gvrpModel){

        $data = $gvrpModel->first();

        return returnMsg(0,'获取成功',$data);

    }

}